package cc.mango.dao;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionHandler implements InvocationHandler
{
	private final static String	CLOSE_METHOD_NAME	= "close";
	private Connection			connection;

	public Connection getConnection()
	{
		return connection;
	}

	private Connection	m_originConnection;

	public Connection getM_originConnection()
	{
		return m_originConnection;
	}

	public void setM_originConnection(Connection m_originConnection)
	{
		this.m_originConnection = m_originConnection;
	}

	ConnectionHandler(Connection con)
	{
		this.connection = (Connection) Proxy.newProxyInstance(con.getClass()
				.getClassLoader(), con.getClass().getInterfaces(), this);
		m_originConnection = con;
	}

	void close() throws SQLException
	{
		m_originConnection.close();
	}

	public Object invoke(Object proxy, Method m, Object[] args)
			throws Throwable
	{
		Object obj = null;
		if (CLOSE_METHOD_NAME.equals(m.getName()))
		{
			ConnectionPool.pushConnectionBackToPool(this);
		}
		else
		{
			obj = m.invoke(m_originConnection, args);
		}
		return obj;
	}
}